<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :tool-button="false" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #state="scope">
        <span v-if="scope.row.state === '1'">已查看</span>
        <el-button v-else type="primary" link @click="openDrawer('查看', scope.row)"> 查看评价 </el-button>
      </template>
      <template #level="scope">
        <span v-if="scope.row.state === '0'">*</span>
        <span v-else>{{ scope.row.level }}</span>
      </template>
      <template #avgScore="scope">
        <span v-if="scope.row.state === '0'">*</span>
        <span v-else>{{ scope.row.avgScore }}</span>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button
          v-if="userUser.userInfo.email === scope.row.userId && scope.row.state === '0'"
          type="primary"
          link
          :icon="EditPen"
          @click="openDrawer('编辑', scope.row)"
          >编辑
        </el-button>
        <el-button
          v-if="userUser.userInfo.email === scope.row.userId && scope.row.state === '0'"
          type="primary"
          link
          :icon="Delete"
          @click="deleteAccount(scope.row)"
          >删除
        </el-button>
      </template>
    </ProTable>
    <ViewDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { RushJob } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import ViewDrawer from "./viewDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { Delete, EditPen, View } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { enumRender, monthRender, userRender } from "@/hooks/useColumnRender";
import { useUserStore } from "@/stores/modules/user";
import { useDataStore } from "@/stores/modules/data";

const initVar = reactive({
  tbName: "performance",
  tbCnName: "绩效评估"
});

// ProTable 实例
const proTable = ref<ProTableInstance>();
const userUser = useUserStore();
const dataStore = useDataStore();

const defaultDate = ref<Date>(new Date());

const initParam = reactive({
  condition: { userId: userUser.userInfo._id },
  options: { sort: { startTime: -1 } }
});

const orgTree = computed(() => dataStore.orgTree);
const userList = computed(() => dataStore.userList);
const isOrNotList = computed(() => dataStore.getEnumByCsName("IS_NOT"));
onMounted(() => {
  dataStore.findUserList();
  dataStore.findOrgTree();
  dataStore.findEnumByCsName("IS_NOT");
});

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (newParams.condition && newParams.condition.performanceDate) {
    let curDate = new Date(newParams.condition.performanceDate);
    let startDate = new Date(curDate.getFullYear(), 0, 0);
    let endDate = new Date(curDate.getFullYear() + 1, 0, 0);
    newParams.condition.performanceDate = { $gte: startDate, $lte: endDate };
  }
  newParams.condition.userId = userUser.userInfo._id;
  return apiService.findPage(initVar.tbName, newParams.condition, newParams.options);
};

// 表格配置项
const columns = reactive<ColumnProps<Performance>[]>([
  { type: "index", label: "序号", width: 85 },
  { prop: "userId", label: "姓名", width: 100, render: scope => userRender(scope, userList) },
  {
    prop: "orgId",
    label: "组织",
    width: 160,
    fieldNames: { label: "name", value: "_id" },
    enum: orgTree
  },
  {
    prop: "performanceType",
    label: "评估类型",
    search: { el: "select", props: { filterable: true } },
    enum: () => apiService.findClassify("performanceType"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "performanceDate",
    label: "绩效周期",
    render: monthRender,
    search: { el: "date-picker", props: { type: "year" }, order: 1, defaultValue: defaultDate, label: "绩效周期" }
  },
  {
    prop: "crossRate",
    label: "评估占比",
    enum: () => apiService.findClassify("crossRate"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "level",
    label: "等级",
    enum: () => apiService.findClassify("PERFORMANCE_LEVEL"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "chat_state",
    label: "是否面谈",
    enum: isOrNotList,
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "avgScore", label: "综合评分" },
  {
    prop: "state",
    label: "是否查看评价",
    minWidth: 120
  },
  { prop: "operation", label: "操作", align: "left", fixed: "right", width: 180 }
]);

// 删除信息
const deleteAccount = async (params: RushJob) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除`);
  proTable.value?.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof ViewDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<RushJob> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: row,
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : apiService.updateById,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
